import React from 'react';
import { connect } from 'react-redux';
import { 
  addTodo, delTodo, changeText, completeTodo,
  editTodo, getEditContent, getEditIndex,
  clearEditContent,
 } from './actions';

function App(props) {
  const { dispatch, todos, inputValue, editIndex } = props;

  function handleClick() {
    if (editIndex === null) {
      if (!inputValue) return;
      dispatch(addTodo(inputValue));
    } else {
      dispatch(editTodo(editIndex, inputValue));
      dispatch(clearEditContent());
    }
  }

  return (
    <div className="note-set">
      <div className="header">
        <input
            className="useript"
            type="text"
            onChange={(event) => dispatch(changeText(event.target.value))}
            value={inputValue}
          />
          <button
            className="btn"
            type="button"
            onClick={handleClick}
          >
            {editIndex === null ? '添加' :  '完成'}
          </button>
      </div>
      <ul className="list-set">
        {
          todos.map((todo, index) => (
          <li className="item" key={index}>
            <i
              className={`item_complete${todo.completed ? ' -active' : ''}`}
              onClick={() => dispatch(completeTodo(index, todo.completed))}
            ></i>
            <span className={`item_text${todo.completed ? ' -active' : ''}`}>{todo.text}</span>
            <span
              className="item_edit"
              onClick={(event) => {
                const value = event.target.previousSibling.textContent;
                dispatch(getEditContent(value));
                dispatch(getEditIndex(index));
              }}
            >
              编辑
            </span>
            <i
              className="item_del"
              onClick={() => dispatch(delTodo(index))}
            ></i>
          </li>
          ))
        }
      </ul>
    </div>
  );
}

function mapStateToProps(state) {
  return {
    todos: state.todos,
    inputValue: state.inputValue,
    editIndex: state.editIndex,
  }
}

export default connect(mapStateToProps)(App);
